package ro.myApp.articles.service.publication;

import java.util.LinkedList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import ro.myApp.articles.dto.PublicationCreateNewMessage;
import ro.myApp.articles.dto.PublicationFindAllMessage;
import ro.myApp.articles.dto.PublicationFindByIdMessage;
import ro.myApp.articles.dto.PublicationSaveNewMessage;
import ro.myApp.articles.entities.Publication;
import ro.myApp.commons.dto.BaseDtoMessage;
import ro.myApp.esb.service.MessageBasedService;
import ro.myApp.esb.service.MessageBasedServiceImpl;


@Local(value=MessageBasedService.class)
@Remote(value=MessageBasedService.class)
@Stateless
public class PublicationsManagementServiceImpl extends MessageBasedServiceImpl{

	@EJB(mappedName="PublicationActionServiceImpl/local")
	private PublicationActionService publicationActionService; 

	@EJB(mappedName="PublicationAccessServiceImpl/local")
	private PublicationAccessService publicationAccessService;
	
	@Override
	protected Object execute(BaseDtoMessage dto) throws Throwable {
		if (dto instanceof PublicationFindByIdMessage)
			return publicationAccessService.findByIdFetchAll (((PublicationFindByIdMessage)dto).getPublicationId());
		if (dto instanceof PublicationSaveNewMessage)
			return publicationActionService.updateEntity(((PublicationSaveNewMessage)dto).getPublication());
		if (dto instanceof PublicationCreateNewMessage){
			Class<Publication> clazz = (Class<Publication>) ((PublicationCreateNewMessage) dto).getClazz();
			return publicationActionService.createOtherEntity(clazz, ((PublicationCreateNewMessage) dto).getUserName());
		}
		if (dto instanceof PublicationFindAllMessage){
			PublicationFindAllMessage msg= (PublicationFindAllMessage) dto;
			List<Criterion>	crit = new LinkedList<Criterion>();
			if (msg.isOnlyPublic())
				crit.add(Restrictions.eq("accessPublic", Boolean.TRUE));
			if (null!=msg.getForRole())
				crit.add(Restrictions.eq("accessRole", msg.getForRole()));
			if (null!=msg.getForUser())
				crit.add(Restrictions.eq("author", msg.getForRole()));
			crit.add(Restrictions.eq("deleted", Boolean.FALSE));
			return publicationAccessService.findFiltered(
					"rating", false,
					((PublicationFindAllMessage) dto).getMaxNumber(), 
					crit.toArray(new Criterion[0]));
		}
		return null;
	}

}
